package com.vs.meepet.network

import android.webkit.MimeTypeMap
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 *
 * 作者：柯嘉少
 * 邮箱：2449926649@qq.com
 * 日期: 2023/11/15
 * 修改人: xxx(des)
 * 说明:
 * 版本: 1.0
 */
class ParamsHelper {
    companion object {
        /**
         * json数据放body而不是form放body
         */
        fun getBodyJson(bean: Any?): RequestBody {
            return RequestBody.create(
                MediaType.parse("application/json; charset=UTF-8"),
                Gson().toJson(bean)
            )
        }

        fun getNullFilePart(fileName: String): MultipartBody.Part {
            val byte = ByteArray(0)
            var imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), byte)
            var imageBodyPart = MultipartBody.Part.createFormData("file", fileName, imageBody)
            return imageBodyPart
        }

        /**
         * 获取带参数的单个文件上传的body
         */
        fun getFileBodyPart(strPath: String): MultipartBody.Part {
            var file = File(strPath);
            var imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            var imageBodyPart = MultipartBody.Part.createFormData("file", file.getName(), imageBody)
            return imageBodyPart
        }

        fun getFileBodyPart(file: File): MultipartBody.Part {
            val imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            return MultipartBody.Part.createFormData("file", file.name, imageBody)
        }

        fun getZipBodyPart(file: File): MultipartBody.Part {
            // fileName 文件名
            val mimeType =
                MimeTypeMap.getSingleton().getMimeTypeFromExtension("zip") ?: "multipart/form-data"

            val imageBody = RequestBody.create(MediaType.parse(mimeType), file)
            return MultipartBody.Part.createFormData("file", file.name, imageBody)
        }

        /**
         * 获取带参数的单个文件上传的body
         */
        fun getFileBodyPart(name: String, strPath: String): MultipartBody.Part {
            var file = File(strPath);
            val imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            var imageBodyPart =
                MultipartBody.Part.createFormData("${name}", file.getName(), imageBody)
            return imageBodyPart
        }

        /**
         * 获取带参数的单个文件上传的body
         */
        fun getFileBodyPart(maps: Map<String, String>, file: File): RequestBody {
            val fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            val body: RequestBody = MultipartBody.Builder()
                .apply {
                    maps.forEach {
                        addFormDataPart(it.key, it.value)
                    }
                }
                .addFormDataPart("file", file.name, fileRQ)
                .build()
            return body
        }
    }
}